import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:in_out_goods_manage/utiles/adapation.dart';

import 'package:charts_flutter_new/flutter.dart' as charts;

import 'package:in_out_goods_manage/utiles/moment.dart';
import 'dart:core';
// 商品信息
import 'package:in_out_goods_manage/model/goods_manage.dart';
import 'package:provider/provider.dart';

class StatisticPage extends HookWidget {
  const StatisticPage({super.key});

  @override
  Widget build(BuildContext context) {
    var goodsManageModel = Provider.of<GoodsManageModel>(context);
    final weekMonth = useState<String>('weeks');
    final inOut = useState<String>('in');
    final seriesData = useState<List<LinearSales>>([]);
    final dateRange = useState('');
    final start = useState<int>(0);
    final end = useState<int>(1);
    // 获取图表数据
    getSeriesData(String weekMonthType, String inOutType) {
      DateTime nowDay = DateTime.now();

      if (weekMonthType == 'weeks') {
        List<int> data = getDatesForThisWeek();

        dateRange.value =
            '${nowDay.month}.${data[0]}~${nowDay.month}.${data[data.length - 1]}';
        start.value = data[0];
        end.value = data[data.length - 1];
        seriesData.value = data.map((e) {
          if (e == nowDay.day) {
            return LinearSales(
                e,
                inOutType == 'in'
                    ? goodsManageModel.addNum
                    : goodsManageModel.reduce);
          } else {
            return LinearSales(e, 0);
          }
        }).toList();
      } else {
        List<int> data = getDatesForThisMonthdays();

        dateRange.value =
            '${nowDay.month}.${data[0]}~${nowDay.month}.${data[data.length - 1]}';
        start.value = data[0];
        end.value = data[data.length - 1];
        seriesData.value = data.map((e) {
          if (e == nowDay.day) {
            return LinearSales(
                e,
                inOutType == 'in'
                    ? goodsManageModel.addNum
                    : goodsManageModel.reduce);
          } else {
            return LinearSales(e, 0);
          }
        }).toList();
      }
    }

    useEffect(() {
      getSeriesData(weekMonth.value, inOut.value);

      return null;
    }, [weekMonth.value, inOut.value]);
    return Scaffold(
      appBar: AppBar(
        centerTitle: true,
        title: SizedBox(
            child: CupertinoSegmentedControl(
          groupValue: weekMonth.value,
          onValueChanged: (val) {
            weekMonth.value = val;
          },
          children: {
            "weeks": Container(
              padding: const EdgeInsets.symmetric(vertical: 3, horizontal: 10),
              child: const Text("week"),
            ),
            "month": Container(
              padding: const EdgeInsets.symmetric(vertical: 3, horizontal: 10),
              child: const Text("month"),
            ),
          },
        )),
      ),
      body: SizedBox(
        width: double.infinity,
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            weekMonth.value == 'weeks'
                ? LineChartsCard(
                    data: seriesData.value,
                    dateRange: dateRange.value,
                    start: start.value,
                    end: end.value,
                    onChange: (val) {
                      inOut.value = val;
                      // getSeriesData(weekMonth.value, inOut.value);
                    },
                  )
                : LineChartsCard(
                    data: seriesData.value,
                    dateRange: dateRange.value,
                    start: start.value,
                    end: end.value,
                    onChange: (val) {
                      inOut.value = val;
                      // getSeriesData(weekMonth.value, inOut.value);
                    },
                  ),
          ],
        ),
      ),
    );
  }
}

class LineChartsCard extends HookWidget {
  const LineChartsCard(
      {super.key,
      required this.data,
      this.dateRange,
      this.year,
      this.start,
      this.end,
      required this.onChange});
  final List<LinearSales> data;
  final String? dateRange;
  final String? year;
  final int? start;
  final int? end;
  final void Function(String) onChange;
  @override
  Widget build(BuildContext context) {
    final tabVal = useState('in');
    return Card(
      color: const Color(0xFFFFFFFF), //卡片的颜色
      elevation: 0, //阴影的大小
      shadowColor: const Color(0xFFEAEAEA), //阴影的颜色
      margin: EdgeInsets.only(top: AdaptSize.px(20)), //外边距
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.all(
          Radius.circular(
            AdaptSize.px(10),
          ),
        ),
      ),
      child: Container(
          padding: EdgeInsets.symmetric(
            vertical: AdaptSize.px(16),
            horizontal: AdaptSize.px(8),
          ),
          width: AdaptSize.px(345),
          child: Column(
            children: [
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Row(
                    children: [
                      Text(year ?? DateTime.now().year.toString()),
                      const SizedBox(
                        height: 15,
                        child: VerticalDivider(),
                      ),
                      Text(dateRange ?? '')
                    ],
                  ),
                  CupertinoSegmentedControl(
                    groupValue: tabVal.value,
                    onValueChanged: (val) {
                      tabVal.value = val;
                      onChange(val);
                    },
                    children: {
                      "in": Container(
                        padding:
                            EdgeInsets.symmetric(horizontal: AdaptSize.px(6)),
                        child: const Text("storage"),
                      ),
                      "out": Container(
                        padding:
                            EdgeInsets.symmetric(horizontal: AdaptSize.px(6)),
                        child: const Text("outStorage"),
                      ),
                    },
                  )
                ],
              ),
              SizedBox(
                height: 240,
                child: _simpleLine(),
              )
            ],
          )),
    );
  }

  Widget _simpleLine() {
    var seriesList = [
      charts.Series<LinearSales, int>(
        id: 'Sales',
        colorFn: (_, __) => charts.MaterialPalette.blue.shadeDefault,
        domainFn: (LinearSales sales, _) => sales.year,
        measureFn: (LinearSales sales, _) => sales.sales,
        data: data,
      )
    ];
    final charts.LineRendererConfig<num> defaultRenderer =
        charts.LineRendererConfig(
      // 圆点大小
      radiusPx: 5.0,
      stacked: false,
      // 线的宽度
      strokeWidthPx: 2.0,
      // 是否显示线
      includeLine: true,
      // 是否显示圆点
      includePoints: true,
      // 是否显示包含区域
      includeArea: true,
      // 区域颜色透明度 0.0-1.0
      areaOpacity: 0.2,
    );

    return charts.LineChart(
      seriesList,
      domainAxis: charts.NumericAxisSpec(
          viewport: charts.NumericExtents(start ?? 0, end ?? data.length + 1)),
      animate: true,
      defaultRenderer: defaultRenderer,
    );
  }
}

class LinearSales {
  final int year;
  final int sales;

  LinearSales(this.year, this.sales);
}
